﻿using System;
using System.Collections.Generic;
using System.Linq;
using ArchPostprocessing.CompoundStructureManage.Managers;
using ArchPostprocessing.CompoundStructureManage.Managers.Controllers;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using HYView;

namespace ArchPostprocessing.CompoundStructureManage.Commands
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdSplitWall : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			CmdViewType types = (CmdViewType)17;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			cmdData.Application.Application.FailuresProcessing += this.OnFailuresProcessing;
			WallSplitController wallSplitController = new WallSplitController(cmdData);
			List<Wall> list = new List<Wall>();
			if (!WallCommon.SelectWalls(cmdData.Application.ActiveUIDocument, ref list))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			for (int i = 0; i < list.Count; i++)
			{
				WallType wallType = list.ElementAt(i).WallType;
				if (wallType == null || wallType.Kind != null)
				{
					list.RemoveAt(i);
					i--;
				}
			}
			if (0 < list.Count)
			{
				wallSplitController.SplitWalls(list);
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void OnFailuresProcessing(object sender, FailuresProcessingEventArgs e)
		{
			FailuresAccessor failuresAccessor = e.GetFailuresAccessor();
			string transactionName = failuresAccessor.GetTransactionName();
			if (failuresAccessor.GetFailureMessages().Count == 0)
			{
				e.SetProcessingResult((FailureProcessingResult)0);
				return;
			}
			if (transactionName.Equals("split wall"))
			{
				failuresAccessor.DeleteAllWarnings();
				e.SetProcessingResult((FailureProcessingResult)1);
				return;
			}
			e.SetProcessingResult((FailureProcessingResult)0);
		}
	}
}
